from django.shortcuts import render

# Create your views here.
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from .forms import ProfileUpdateForm
from .models import CustomUser
from blog.models import Post


@login_required
def profile(request):
    """用户个人资料页面"""
    user_posts = Post.objects.filter(author=request.user).order_by('-created_at')

    if request.method == 'POST':
        form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user)
        if form.is_valid():
            form.save()
            messages.success(request, '个人资料已更新！')
            return redirect('profile')
    else:
        form = ProfileUpdateForm(instance=request.user)

    context = {
        'form': form,
        'user_posts': user_posts
    }
    return render(request, 'users/profile.html', context)


def user_detail(request, username):
    """查看其他用户的资料页面"""
    user = get_object_or_404(CustomUser, username=username)
    user_posts = Post.objects.filter(author=user, status='published').order_by('-created_at')

    context = {
        'profile_user': user,
        'user_posts': user_posts
    }
    return render(request, 'users/user_detail.html', context)

